package com.tramy.data.export.engine.impl;

import com.tramy.data.export.datasource.DatabaseContextHolder;
import com.tramy.data.export.datasource.DatabaseType;
import com.tramy.data.export.engine.DataEngine;
import com.tramy.data.export.mapper.StoreMapper;
import com.tramy.data.export.mapper.TramyStoreMapper;
import com.tramy.data.export.model.Store;
import com.tramy.data.export.model.StoreExample;
import com.tramy.data.export.model.TramyStore;
import com.tramy.data.export.model.TramyStoreExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by honway on 2016/11/3.
 */
@Service
public class CustomerDataEngine implements DataEngine {


    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private TramyStoreMapper tramyStoreMapper;

    @Override
    public void justDoIt() {
        DatabaseContextHolder.setDatabaseType(DatabaseType.firehome);
        //因为客户数据比较多,所以分批处理
        int batchSize = 2000;
        StoreExample storeExample = new StoreExample();
        storeExample.createCriteria().andStoreCodeIsNotNull();
        int count = storeMapper.countByExample(storeExample);
        System.out.println("总数据量:"+count);
        List<Store> stores = storeMapper.selectByExample(storeExample);
        List<TramyStore> tramyStores = stores.parallelStream().map(Store::convert).collect(Collectors.toList());
        proceedTramyStores(tramyStores);

        /*int loopTimes = count / batchSize;
        for (int i = 0; i <= loopTimes; i++) {
            DatabaseContextHolder.setDatabaseType(DatabaseType.firehome);
            StoreExample example = new StoreExample();
            example.createCriteria().andStoreCodeIsNotNull();
            example.setOrderByClause("store_Id");
            List<Store> firehomeResult = storeMapper.pageSelect(i+1,batchSize);
            System.out.println("分页查询结果大小:"+firehomeResult.size());
            List<TramyStore> tramyStores = firehomeResult.parallelStream().map(Store::convert).collect(Collectors.toList());

            proceedTramyStores(tramyStores);
        }*/
    }

    /**
     * 处理新清美数据入库
     * @param tramyStores 新清美数据
     */
    private void proceedTramyStores(List<TramyStore> tramyStores) {
        DatabaseContextHolder.setDatabaseType(DatabaseType.pinshang);
        tramyStores.parallelStream().map(store -> {
            TramyStoreExample tramyStoreExample = new TramyStoreExample();
            tramyStoreExample.createCriteria().andStoreCodeEqualTo(store.getStoreCode());
            List<TramyStore> tramyStoreList = tramyStoreMapper.selectByExample(tramyStoreExample);
            if (tramyStoreList.size() == 0) {
                tramyStoreMapper.insertSelective(store);
            }
            return 1;
        }).count();
    }
}
